//app.js
require("utils/md5.js");
var t = require("utils/moment.js");
require("utils/formate.js");
var session = require('/utils/session.js');

App({

  first: 0,
  arr: [],
  steps: 0,
  mobilereg: /^((14[0-9])|166|(17[0-8])|(13[0-9])|(15[0-9])|(18[0-9])|191|199|198)\d{8}$/,
  guardedAlarm: "警戒模式",
  nomalAlarm: "正常模式",
  dndAlarm: "免打扰模式",
  synAlarm: "与账号配置一致",
  guardedAlarmTip: "接收微信报警、电话报警",
  nomalAlarmTip: "接收微信报警、电话报警(拆机报警)",
  dndAlarmTip: "不再接收微信报警、电话报警",
  status_motionless: 0,
  status_move: 1,
  status_sleep: 2,
  status_unused: 20,
  status_offline: 10,
  mapType: 0,
  defaultTempDefenceTimeItems: [{
    name: "半小时",
    value: "1800"
  }, {
    name: "一小时",
    value: "3600"
  }, {
    name: "两小时",
    value: "7200"
  }],
  directionItems: {
    poweroff: 15,
    poweron: 16
  },
  system: {
    source: 2,
    app_name: "运输车管控",
    app_url_prefix: "http://47.111.106.172:8080",
    official_account: "护车宝位置服务",
    image_prefix: "hcbxcws",
    color: "#f74653",
    playColor: "#f74653",
    appid: "wx918db9fd9c4cab8c"
  },

  /**
   * 当小程序初始化完成时，会触发 onLaunch（全局只触发一次）
   */
  onLaunch: function () {
    let that = this
    let car = session.currentCar() 

    if (car){
      wx.reLaunch({
        url: '/pages/home/index/index',
      }) 
    } else {
      if (session.getIsFirstLaunch() ){
        wx.reLaunch({
          url: '/pages/assessment/index/index',
        }) 
      } else {
        wx.redirectTo({
          url: '/pages/login/index/index',
        })
      }
    }
  },

  /**
   * 当小程序启动，或从后台进入前台显示，会触发 onShow
   */
  onShow: function (options) {
    
  },

  /**
   * 当小程序从前台进入后台，会触发 onHide
   */
  onHide: function () {
    
  },

  /**
   * 当小程序发生脚本错误，或者 api 调用失败时，会触发 onError 并带上错误信息
   */
  onError: function (msg) {
    
  },

  getUserInfo: function (t) {
    var e = this;
    this.globalData.userInfo ? "function" == typeof t && t(this.globalData.userInfo) : wx.getUserInfo({
      withCredentials: !1,
      success: function (s) {
        e.globalData.userInfo = s.userInfo, "function" == typeof t && t(e.globalData.userInfo);
      }
    });
  },
  globalData: function (t) {
    for (var e in this.status) if (Number(e) === Number(t)) return this.status[e];
    return this.status;
  },
  getPromission: function () {
    wx.getSetting({
      success: function (t) {
        t.authSetting["scope.userLocation"] || wx.openSetting({
          success: function (t) { }
        });
      }
    });
  },

  getAccessToken: function (e) {
    var s = this, n = wx.getStorageSync("time"), a = wx.getStorageSync("expiresIn"), o = wx.getStorageSync("accessToken"), c = t().unix();
    if (n && a && o && c - n < a / 1e3 - 120 && e instanceof Function) e(); else new Promise(function (t, n) {
      wx.getUserInfo({
        success: function (n) {
          var a = encodeURIComponent(n.encryptedData), o = encodeURIComponent(n.iv);
          wx.login({
            success: function (n) {
              wx.request({
                url: s.system.app_url_prefix + "/rest/wx/ticket/applet/auth?code=" + n.code + "&type=" + s.system.source + "&encryptedData=" + a + "&iv=" + o,
                data: {},
                method: "POST",
                header: {
                  Accept: "application/json",
                  "Content-Type": "application/json; charset=utf-8"
                },
                success: function (s) {
                  if (200 != s.statusCode) return 
                  wx.showModal({
                    title: "提示",
                    content: "微信认证失败",
                    showCancel: !1,
                    success: function (t) { }
                  }), void t(null);
                  s && (wx.setStorageSync("accessToken", s.data.accessToken), wx.setStorageSync("time", s.data.time),
                    wx.setStorageSync("expiresIn", s.data.expiresIn), wx.setStorageSync("wechatOpenid", s.data.openId),
                    wx.setStorageSync("unionId", s.data.unionId), e instanceof Function && e()), t(null);
                },
                fail: function (e) {
                  wx.showModal({
                    title: "提示",
                    content: "微信认证失败",
                    showCancel: !1,
                    success: function (t) { }
                  }), t(null);
                }
              });
            },
            fail: function () {
              console("微信认证失败"), t(null);
            }
          });
        }
      }), t(null);
    });
  },

  getLocationTypeText: function (t) {
    var e = "";
    switch (t.locationType) {
      case 0:
        e = "基站定位";
        break;

      case 1:
        e = "GPS定位";
        break;

      case 2:
        e = "WiFi定位";
    }
    return e;
  },

  getStatusText: function (t) {
    var e = "";
    return t ? t.status === this.status_unused ? e = "未启用" : t.status === this.status_move ? e = "行驶 " + t.speed + "km/h" : t.status === this.status_motionless || t.status === this.status_sleep ? e = "在线 " : t.status === this.status_offline && (e = "离线 ") : e = "未启用",
      e;
  },

  getAccStatusText: function (t) {
    var e = "";
    if (!t) return e;
    var s = !!t.hasOwnProperty("accStatus");
    return t.status == this.status_offline ? e = "离线" : s && (e = t.accStatus ? "开" : "关"),
      e;
  },

  convertCycleText: function (t) {
    return "0000000" == t ? "永不" : "1111111" == t ? "每天" : "1111100" == t ? "工作日" : "0000011" == t ? "周末" : this.getOtherCycleText(t);
  },

  getOtherCycleText: function (t) {
    var e = "";
    return 1 == t.charAt(0) && (e += "周一 "), 1 == t.charAt(1) && (e += "周二 "), 1 == t.charAt(2) && (e += "周三 "),
      1 == t.charAt(3) && (e += "周四 "), 1 == t.charAt(4) && (e += "周五 "), 1 == t.charAt(5) && (e += "周六 "),
      1 == t.charAt(6) && (e += "周日 "), e;
  },

  getUserDevice: function (callback) {
    let that = this
    let openId = wx.getStorageSync("wechatOpenid")
    if(!openId){
      return
    }
    wx.request({
      url: that.system.app_url_prefix + "/weapp/transport/homePage?openId=" + openId,
      method: "POST",
      data: {},
      header: {
        Accept: "application/json",
        "Content-Type": "application/json; charset=utf-8"
      },
      success: function (e) {
        let code = parseInt(e.data.code)
        let car = JSON.stringify(e.data.data)
        code == 0 
        ? (
          session.setCurrentCar(car),
            typeof callback == 'function' && callback(car)
          ) 
          : typeof callback == 'function' && callback()
      },
      fail: function (e) { },
      complete: function (e) {
        wx.hideLoading();
      }
    })
  }
})